/**
 * @author yadongzhao87
 * @date 2023-10-19
 * 清雷毫米波雷达相关接口
 */
const {
  InfluxDB,
  flux,
  fluxDuration
} = require('@influxdata/influxdb-client');
const returnData = require("../util/returnstring");
const dotenv = require("dotenv");
dotenv.config({ path: `.env.${process.env.NODE_ENV}` })
// const redis = new Redis({
//     port: process.env.REDIS_PORT,
//     host: process.env.REDIS_HOST,
//     password: process.env.REDIS_PASSWORD,
//     db: process.env.REDIS_DB
// })
const router = require('koa-router')();

const url = process.env.INFLUXDB_URL;
const token = process.env.INFLUXDB_TOKEN;
const org = process.env.INFLUXDB_ORG;
const haomibolist = require("../config/haomibo");
const hujiaolist=require("../config/hujiao");
const queryApi = new InfluxDB({
  url,
  token
}).getQueryApi(org)


// 定义路由前缀，没有可不添加
router.prefix('/api/room');
// 获取清雷的生命体征信息回调
router.get('/smtz', async (ctx, next) => {
  let radarData = [];
  const {
      building_name = 0, floor = 0
  } = ctx.query;
  const start = fluxDuration('-1h')
  const fluxQuery = flux`from(bucket:"iot") 
|> range(start: ${start}) 
|> filter(fn: (r) => r["_measurement"] == "radar_shengming")
|> filter(fn: (r) => r["statusName"] == "睡觉" or r["statusName"] == "清醒")
|> pivot(
  rowKey:["_time"],
  columnKey: ["_field"],
  valueColumn: "_value")`
  try {
      for await (const {
          values,
          tableMeta
      } of queryApi.iterateRows(fluxQuery)) {
          const o = tableMeta.toObject(values)
          let newtime = new Date(o._time);
          o.newtime = newtime.getTime();
          setRadarData(o);
      }
      console.log('\nFinished SUCCESS')
  } catch (e) {
      console.log('\nFinished ERROR')
  }
  const latestRadarData = await getLatestRadarData();
  
  let returnDataArr = {};
  for (let key in latestRadarData) {
      if (haomibolist[key]) {
          if (building_name && haomibolist[key]["building_name"] == building_name && floor && haomibolist[key]["floor"] == floor) {
              returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
          } else if (building_name && haomibolist[key]["building_name"] == building_name && floor == 0) {
              returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
          } else if (building_name == 0) {
              returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
          }
      }
  }
  ctx.body = returnData(100000, returnDataArr, "");
  console.log(1)
  /**
* 设置雷达数据
* @param {Object} oData 
*/
  function setRadarData(oData) {
      radarData.push(oData);
  }
  /**
   * 返回本次查询中最新的一条数据
   */
  function getLatestRadarData() {
      let result = [];
      for (let i = 0; i < radarData.length; i++) {
          if (!result[radarData[i].snCode]) {
              result[radarData[i].snCode] = {};
          }
          radarData[i].statusName ? result[radarData[i].snCode]["statusName"] = radarData[i].statusName : null;
          radarData[i].breathBpm ? result[radarData[i].snCode]["breathBpm"] = radarData[i].breathBpm : null;
          radarData[i].breathBpmRange ? result[radarData[i].snCode]["breathBpmRange"] = radarData[i].breathBpmRange : null;
          radarData[i].heartBpm ? result[radarData[i].snCode]["heartBpm"] = radarData[i].heartBpm : null;
          radarData[i].heartBpmRange ? result[radarData[i].snCode]["heartBpmRange"] = radarData[i].heartBpmRange : null;
          radarData[i].inOutBed ? result[radarData[i].snCode]["inOutBed"] = radarData[i].inOutBed : null;
          radarData[i].outBedDuration ? result[radarData[i].snCode]["outBedDuration"] = radarData[i].outBedDuration : null;
          radarData[i].tooCloseFlag ? result[radarData[i].snCode]["tooCloseFlag"] = radarData[i].tooCloseFlag : null;
          // radarData[i].alarmTime ? result[radarData[i].snCode]["alarmTime"] = radarData[i].alarmTime : null;
          // radarData[i].alarmType ? result[radarData[i].snCode]["alarmType"] = radarData[i].alarmType : null;
          // radarData[i].exist ? result[radarData[i].snCode]["inOutBathroom"] = radarData[i].exist : null;
          // radarData[i].fall ? result[radarData[i].snCode]["fall"] = radarData[i].fall : null;
      }
      return result;
  }
})
router.get('/alarmlist', async (ctx, next) => {
    let radarData = [];
    const {
        building_name = 0, floor = 0
    } = ctx.query;
    //根据房间号获得设备绑定关系
    const start = fluxDuration('-1m')
    const fluxQuery = flux`from(bucket:"iot") 
  |> range(start: ${start}) 
  |> filter(fn: (r) => r["_measurement"] == "hujiao" or r["_measurement"] == "radar_ddjc" or r["_measurement"] == "radar_ssbj")
  |> pivot(
    rowKey:["_time"],
    columnKey: ["_field"],
    valueColumn: "_value")`
    try {
        for await (const {
            values,
            tableMeta
        } of queryApi.iterateRows(fluxQuery)) {
            const o = tableMeta.toObject(values)
            let newtime = new Date(o._time);
            o.newtime = newtime.getTime();
            setRadarData(o);
        }
        console.log('\nFinished SUCCESS')
    } catch (e) {
        console.log(e);
        console.log('\nFinished ERROR')
    }
    const latestRadarData = await getLatestRadarData();
    let returnDataArr = {};
    for (let key in latestRadarData) {
       if(Object.keys(latestRadarData[key]).length!=0){
        if (haomibolist[key]) {
            if (building_name && haomibolist[key]["building_name"] == building_name && floor && haomibolist[key]["floor"] == floor) {
                returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
            } else if (building_name && haomibolist[key]["building_name"] == building_name && floor == 0) {
                returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
            } else if (building_name == 0) {
                returnDataArr[haomibolist[key]["building_name"] + "-" + haomibolist[key]["room_no"] + "-" + haomibolist[key]["bed_no"]] = latestRadarData[key];
            }
        }if(hujiaolist[key]){
            if (building_name && hujiaolist[key]["building_name"] == building_name && floor && hujiaolist[key]["floor"] == floor) {
                returnDataArr[hujiaolist[key]["building_name"] + "-" + hujiaolist[key]["room_no"] + "-" + hujiaolist[key]["bed_no"]] = latestRadarData[key];
            } else if (building_name && hujiaolist[key]["building_name"] == building_name && floor == 0) {
                returnDataArr[hujiaolist[key]["building_name"] + "-" + hujiaolist[key]["room_no"] + "-" + hujiaolist[key]["bed_no"]] = latestRadarData[key];
            } else if (building_name == 0) {
                returnDataArr[hujiaolist[key]["building_name"] + "-" + hujiaolist[key]["room_no"] + "-" + hujiaolist[key]["bed_no"]] = latestRadarData[key];
            }
        }}
    }
    ctx.body = returnData(100000, returnDataArr, "");
    /**
 * 设置雷达数据
 * @param {Object} oData 
 */
    function setRadarData(oData) {
        radarData.push(oData);
    }
    /**
     * 返回本次查询中最新的一条数据
     */
    function getLatestRadarData() {
        let result = [];
       
        for (let i = 0; i < radarData.length; i++) {
            if (!result[radarData[i].snCode]) {
                result[radarData[i].snCode] = {};
            }
            radarData[i].alarmTime ? result[radarData[i].snCode]["alarmTime"] = radarData[i].alarmTime : null;
            radarData[i].alarmType ? result[radarData[i].snCode]["alarmType"] = radarData[i].alarmType : null;
            // radarData[i].exist ? result[radarData[i].snCode]["inOutBathroom"] = radarData[i].exist : null;
            radarData[i].fall ? result[radarData[i].snCode]["fall"] = radarData[i].fall : null;
            radarData[i].callUUID ? result[radarData[i].snCode]["callUUID"] = radarData[i].callUUID : null;
        }
        return result;
    }
})

module.exports = router;